# -*-coding:utf-8 -*-

from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.http.formdata import FormFile
from huaweicloudsdkfrs.v2.region.frs_region import FrsRegion
from huaweicloudsdkfrs.v2 import FrsClient, CompareFaceByFileRequestBody, CompareFaceByFileRequest
from huaweicloudsdkcore.exceptions import exceptions
import os

currentDir = os.environ["RUNTIME_CODE_ROOT"]
imgDict = {
    'file1': currentDir+'/data/person_1.png',
    'file2': currentDir+'/data/person_2.png',
}


def handler(event, context):
    """
    人脸比对,输出任务相似度，一般认为大于0.93即为同一个人
    Facial comparison. A person whose similarity is greater than 0.93 is generally regarded as the same person.
    :return:
    """
    log = context.getLogger()
    ak = context.getAccessKey()
    sk = context.getSecretKey()

    projectId = context.getProjectID()
    region = context.getUserData('region')

    if ak is None or sk is None:
        ak = context.getUserData('ak').strip()
        sk = context.getUserData('sk').strip()
        if ak is None or sk is None:
            raise Exception("ak/sk empty, check your function agency")

    if projectId is None:
        raise Exception("projectId empty.")

    if region is None:
        raise Exception("region empty.")

    credentials = BasicCredentials(ak, sk) \

    client = FrsClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(FrsRegion.value_of(region)) \
        .build()
    # 构建请求
    try:
        img1 = FormFile(open(imgDict['file1'],'rb'))
        img2 = FormFile(open(imgDict['file2'],'rb'))
        body = CompareFaceByFileRequestBody(img1,img2)
        request = CompareFaceByFileRequest(body=body)
        response = client.compare_face_by_file(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)
        return "error"
    
    return "success"